package com.fine.hair.applet.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fine.hair.applet.mapper.*;
import com.fine.hair.applet.service.OrderTaskService;
import com.fine.hair.comm.dto.*;
import com.fine.hair.comm.enums.OrderStatus;
import com.fine.hair.comm.enums.RewardsPunishmentType;
import com.fine.hair.comm.exception.BusinessException;
import com.fine.hair.comm.utils.ApiResponse;
import com.fine.hair.comm.utils.DateUtils;
import com.fine.hair.comm.utils.PageInfo;
import com.fine.hair.comm.vo.*;
import com.fine.hair.comm.model.Branch;
import com.fine.hair.comm.model.Order;
import com.fine.hair.comm.model.RewardsPunishment;
import com.fine.hair.comm.model.User;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>员工控制层</p>
 *
 * @author mouseyCat
 * @date 2020/10/4 15:53
 */
@Slf4j
@Api(tags = {"员工相关接口"})
@RestController
@RequestMapping("/staff/")
public class StaffController {

    @Resource
    private UserMapper userMapper;


    @Resource
    private OrderMapper orderMapper;

    @Resource
    private RewardsPunishmentMapper rewardsPunishmentMapper;

    @Resource
    private BranchMapper branchMapper;

    @Autowired
    private OrderTaskService orderTaskService;

    //@PostMapping("apply-staff")
    //@ApiOperation(value = "用户申请成为员工",notes = "废除")
    //public ApiResponse applyStaff(@RequestBody ApplyStaffDto dto) {
    //    // 判断该用户是否员工
    //    User user = userMapper.selectById(dto.getUserId());
    //    if (user.getBranchId() == null) {
    //        return ApiResponse.ofStatus(MyStatus.WAS_STAFF);
    //    }
    //    Apply apply = new Apply();
    //    BeanUtil.copyProperties(dto,apply);
    //    apply.setId(snowflake.nextId());
    //    apply.setApplyStatus(ApplyStatus.WAIT.getCode());
    //    applyMapper.insert(apply);
    //    return ApiResponse.ofSuccess();
    //}

    @ApiOperation("员工查看自己负责的订单")
    @PostMapping("staff-order-list")
    public ApiResponse<PageInfo<StaffOrderVo>> staffOrder(@RequestBody StaffOrderListDto dto) {
        PageInfo<StaffOrderVo> pageInfo = new PageInfo<>(dto.getPageCurr(), dto.getPageSize());
        List<Order> staffOrderList = orderMapper.selectStaffOrder(pageInfo, dto.getStaffId(), dto.getOrderStatus(), dto.getBranchTitle());
        List<StaffOrderVo> vos = Lists.newArrayList();
        for (Order record : staffOrderList) {
            User user = userMapper.selectById(record.getUserId());
            log.info(">>>>>>>>>>>>>>>user {}", user);
            StaffOrderVo vo = new StaffOrderVo();
            vo.setCustomerName(user.getNickName().charAt(0) + ("男".equals(user.getSex()) ? "先生" : "女士"));
            vo.setCustomerPhone(user.getPhoneNumber());
            vo.setOrderStatus(Integer.valueOf(record.getOrderStatus()));
            vo.setTechnicianAvatar(record.getTechnicianAvatar());
            vo.setTechnicianName(record.getTechnicianName());
            vo.setTechnicianPhone(record.getTechnicianPhone());
            vo.setItemTitle(record.getItemTitle());
            vo.setCustomerId(user.getId());
            SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm");
            String format = df.format(record.getExecuteTime());
            String week = DateUtils.calculateWeekDay(Integer.parseInt(format.split(" ")[0].split("\\.")[0]), Integer.parseInt(format.split(" ")[0].split("\\.")[1]), Integer.parseInt(format.split(" ")[0].split("\\.")[2]));
            String dayTime = DateUtils.dayTime(Integer.parseInt(format.split(" ")[1].split(":")[0]));
            vo.setDate(format.split(" ")[0]);
            vo.setTime(week + dayTime + format.split(" ")[1]);
            vo.setTitle(record.getBranchTitle());
            vos.add(vo);
        }
        pageInfo.setRecords(vos);
        return ApiResponse.ofSuccess(pageInfo);
    }



    @ApiOperation("用户查看自己的订单的数量")
    @PostMapping("user-order-count")
    public ApiResponse<UserOrderCountVO> userOrderCount(@RequestBody UserOrderCountDTO dto) {
        UserOrderCountVO userOrderCountVO = new UserOrderCountVO();
        List<Order> userOrderList = orderMapper.selectUserOrderCount(dto.getUserId(), dto.getDate());
        int willStartCount = 0;
        int startingCount = 0;
        int completedCount = 0;
        int cancelCount = 0;
        for (Order order : userOrderList) {
            if (order.getOrderStatus().equals(OrderStatus.WILL_COMPLETE.getCode().toString())) {
                willStartCount ++;
            }
            if (order.getOrderStatus().equals(OrderStatus.COMPLETED.getCode().toString())) {
                completedCount ++;
            }
            if (order.getOrderStatus().equals(OrderStatus.CANCELED.getCode().toString())) {
                cancelCount ++;
            }
            if (order.getOrderStatus().equals(OrderStatus.STARTING.getCode().toString())) {
                startingCount ++;
            }
        }
        userOrderCountVO.setCancelCount(cancelCount);
        userOrderCountVO.setWillStartCount(willStartCount);
        userOrderCountVO.setStartingCount(startingCount);
        userOrderCountVO.setCompletedCount(completedCount);
        return ApiResponse.ofSuccess(userOrderCountVO);

    }

    @ApiOperation("员工挂店-点击入驻")
    @PostMapping("staff-put-branch")
    public ApiResponse staffPutBranch(@RequestBody StaffPutBranchDto dto) {
        User user = userMapper.selectById(dto.getStaffId());
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException("当前用户不存在");
        }
        user.setPutBranchId(dto.getBranchId());
        userMapper.updateById(user);
        return ApiResponse.ofSuccess();
    }


    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("员工确认订单")
    @PostMapping("staff-confirm-order")
    public ApiResponse staffConfirmOrder(@RequestBody StaffConfirmOrderDto dto) {
        Order order = orderMapper.selectById(dto.getOrderId());
        if (!order.getOrderStatus().equals(OrderStatus.WILL_COMPLETE.getCode().toString())) {
            return ApiResponse.of(0,"当前订单不可确认",null);
        }
        User user = userMapper.selectById(order.getUserId());
        order.setOrderStatus(OrderStatus.COMPLETED.getCode().toString());
        orderTaskService.updateUserServiceCount(user, order);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation("员工取消订单")
    @PostMapping("staff-cancel-order")
    public ApiResponse staffCancelOrder(@RequestBody StaffCancelOrderDto dto) {
        Order order = orderMapper.selectById(dto.getOrderId());
        if (ObjectUtil.isNull(order)){
            return ApiResponse.of(0,"订单不存在",null);
        }
        if (!order.getOrderStatus().equals(OrderStatus.WILL_COMPLETE.getCode().toString())) {
            return ApiResponse.of(0,"订单状态已不可更改",null);
        }
        order.setOrderStatus(OrderStatus.CANCELED.getCode().toString());
        orderMapper.updateById(order);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation("员工查询自己的奖惩列表")
    @PostMapping("staff-rewards-punishment-list")
    public ApiResponse<StaffRewardsPunishmentListVo> staffRewardsPunishmentList(@RequestBody StaffRewardsPunishmentListDto dto) {
        List<RewardsPunishment> rewardsPunishments =
                rewardsPunishmentMapper.selectList(new LambdaQueryWrapper<RewardsPunishment>().eq(RewardsPunishment::getUserId, dto.getStaffId()));
        // 分别分成 提成、奖励、惩罚 三个 list 返回给前端
        // 奖励
        List<RewardsPunishment> rewardsList =
                rewardsPunishments.stream().filter(a -> a.getType().equals(RewardsPunishmentType.AWARD.getCode())).collect(Collectors.toList());
        // 惩罚
        List<RewardsPunishment> punishmentList =
                rewardsPunishments.stream().filter(a -> a.getType().equals(RewardsPunishmentType.PUNISHMENT.getCode())).collect(Collectors.toList());
        // 提成
        List<RewardsPunishment> proportionList =
                rewardsPunishments.stream().filter(a -> a.getType().equals(RewardsPunishmentType.PROPORTION.getCode())).collect(Collectors.toList());
        StaffRewardsPunishmentListVo vo = new StaffRewardsPunishmentListVo();
        vo.setProportionList(rewardsList);
        vo.setPunishmentList(punishmentList);
        vo.setRewardsList(proportionList);
        return ApiResponse.ofSuccess(vo);
    }

    @ApiOperation("今日业绩")
    @GetMapping("today-performance/{staffId}")
    public ApiResponse<TodayPerformanceVo> todayPerformance(@PathVariable String staffId ) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        User user = userMapper.selectById(staffId);
        // 当日订单
        List<Order> orders = orderMapper.selectOrderByDate(df.format(new Date()),null);
        // 当日店均
        BigDecimal branchAllMoney = orders.stream().filter(o -> o.getBranchId().equals(user.getBranchId().toString())).map(Order::getItemPrice).reduce(BigDecimal.ZERO,BigDecimal::add);
        // 当日接单客户
        long orderCount = orders.stream().filter(o -> o.getTechnicianId().equals(staffId.toString())).count();

        // 人均
        long personCount =
                orders.stream().filter(o -> o.getBranchId().equals(user.getBranchId().toString())).map(Order::getTechnicianId).distinct().count();
        BigDecimal personAvg;
        if (personCount == 0) {
            personAvg = BigDecimal.ZERO;
        } else {
            personAvg = branchAllMoney.divide(new BigDecimal(String.valueOf(personCount)), 2, BigDecimal.ROUND_HALF_UP);
        }
        // 当日奖惩列表
        List<RewardsPunishment> rewardsPunishments =
                rewardsPunishmentMapper.selectByDate(df.format(new Date()),null);
        // 当日提成
        BigDecimal pm = rewardsPunishments.stream().filter(r -> r.getUserId().equals(staffId)).filter(r -> r.getType().equals(RewardsPunishmentType.PROPORTION.getCode())).map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
        // 奖励金额
        BigDecimal rewards = rewardsPunishments.stream().filter(r -> r.getUserId().equals(staffId)).filter(r -> r.getType().equals(RewardsPunishmentType.AWARD.getCode())).map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
        // 惩罚金额
        BigDecimal punishment = rewardsPunishments.stream().filter(r -> r.getUserId().equals(staffId)).filter(r -> r.getType().equals(RewardsPunishmentType.PUNISHMENT.getCode())).map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
        // 个人当日收入
        BigDecimal selfIncome = pm.add(rewards).subtract(punishment);
        TodayPerformanceVo vo = TodayPerformanceVo.builder()
                .orderCount(orderCount)
                .branchAllMoney(branchAllMoney)
                .personAvg(personAvg)
                .pm(pm)
                .punishment(punishment)
                .rewards(rewards)
                .selfIncome(selfIncome)
                .build();
        return ApiResponse.ofSuccess(vo);
    }

    @PostMapping("staff-search-client-order")
    @ApiOperation(value = "员工查询客户订单", notes = "正在服务、未服务、已完成均调用此接口")
    public ApiResponse<PageInfo<StaffSearchClientOrderVo>> staffSearchClientOrder(@RequestBody StaffSearchClientOrderDto dto) {
        PageInfo<StaffSearchClientOrderVo> pageInfo = new PageInfo<>(dto.getPageCurr(), dto.getPageSize());
        List<StaffSearchClientOrderVo> vos = orderMapper.staffSearchClientOrder(pageInfo, dto.getMode(), dto.getStaffId());
        for (StaffSearchClientOrderVo vo : vos) {
            if (dto.getMode() == 1) {
                vo.setServiceType("正在服务");
            }
            if (dto.getMode() == 2) {
                vo.setServiceType("未服务");
            }
            if (dto.getMode() == 3) {
                vo.setServiceType("已完成");
            }
        }
        pageInfo.setRecords(vos);
        return ApiResponse.ofSuccess(pageInfo);
    }

    @GetMapping("click-remark/{orderId}")
    @ApiOperation(value = "点击备注", notes = "点击备注后进入的页面所需信息")
    public ApiResponse<ClickRemarkVo> clickRemark(@PathVariable Long orderId) {
        ClickRemarkVo vo = orderMapper.clickRemark(orderId);
        return ApiResponse.ofSuccess(vo);
    }

    @PostMapping("edit-remark")
    @ApiOperation(value = "确认修改备注", notes = "点击备注后进入的页面所需信息")
    public ApiResponse<ClickRemarkVo> editRemark(@RequestBody EditRemarkDto dto) {
        Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getId, dto.getOrderId()));
        if (ObjectUtil.isNull(order)) {
            return ApiResponse.of(0,"该订单不存在",null);
        }
        order.setRemark(dto.getRemark());
        orderMapper.updateById(order);
        return ApiResponse.ofSuccess();
    }

    @PostMapping("search-calendar")
    @ApiOperation("查询日历")
    public ApiResponse<List<SearchCalendarVO>> searchCalendar(@RequestBody SearchCalendarDto dto) {
        log.info(">>>>>>>>>>>>>>search-calendar  {}", dto);
        dto.setDate(dto.getDate() + "-01");
        List<SearchCalendarVO> listSearchCalendarVO = Lists.newArrayList();
        List<Order> orderList = orderMapper.selectOrderByMonth(dto);
        for (Order order : orderList) {
            SearchCalendarVO searchCalendarVO = new SearchCalendarVO();
            searchCalendarVO.setDate(order.getExecuteTime().getDate());
            searchCalendarVO.setMonth(order.getExecuteTime().getMonth() + 1);
            searchCalendarVO.setYear(1900 + order.getExecuteTime().getYear());
            searchCalendarVO.setOrderStatus(Integer.parseInt(order.getOrderStatus()));
            listSearchCalendarVO.add(searchCalendarVO);
        }
        log.info(">>>>>>>>>>>>>>search-calendar response {}", listSearchCalendarVO);
        return ApiResponse.ofSuccess(listSearchCalendarVO);
    }


    @GetMapping("staff-client-classification/{staffId}")
    @ApiOperation("员工的客户分类")
    public ApiResponse<StaffClientClassificationVo> staffClientClassification(@PathVariable Long staffId) {
        User user = userMapper.selectById(staffId);
        Branch branch = branchMapper.selectById(user.getBranchId());
        if (branch == null) {
            return ApiResponse.of(0,"该用户非门店员工",null);
        }
        List<Order> orders = orderMapper.selectList(new LambdaQueryWrapper<Order>().eq(Order::getBranchId,
                branch.getId()).eq(Order::getTechnicianId, staffId));
        long countService = orders.stream().filter(o -> o.getOrderStatus().equals(OrderStatus.COMPLETED.getCode().toString())).count();
        StaffClientClassificationVo vo = new StaffClientClassificationVo();
        vo.setBranchTitle(branch.getTitle());
        vo.setCountSerivce(countService);
        return ApiResponse.ofSuccess(vo);
    }

    @GetMapping("/on-work/{userId}")
    @ApiOperation("当前员工是否上班,返回true时为上班状态，false时为下班状态")
    public ApiResponse isOnWork(@PathVariable String userId) {
        User user = userMapper.selectById(userId);
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException("当前用户不存在");
        }
        if(user.getOnWork().equals(1)) {
            return ApiResponse.ofSuccess(true);
        } else {
            return ApiResponse.ofSuccess(false);
        }
    }

}
